package logic

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"time"
	"xialou_platform/app/errorx"
	"xialou_platform/app/tools"
	"xialou_platform/services/wallet/model"

	"xialou_platform/services/wallet/rpc/internal/svc"
	"xialou_platform/services/wallet/rpc/walletClient"

	"github.com/zeromicro/go-zero/core/logx"
)

type WalletWithdrawLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWalletWithdrawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WalletWithdrawLogic {
	return &WalletWithdrawLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 钱包提现
func (l *WalletWithdrawLogic) WalletWithdraw(in *walletClient.WalletWithdrawReq) (*walletClient.EmptyBody, error) {
	wallet, err := l.svcCtx.WalletModel.FindOneBySourceId(l.ctx, in.SourceId)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, errorx.NewReasonError("你没有足够的余额可以提现哦。", err.Error())
		}
		return nil, errorx.NewReasonError("网络出小差了，请重试刷新再试。", err.Error())
	}
	if wallet.Status != 1 {
		return nil, errorx.NewDefaultError("你钱包状态异常，请联系客服。")
	}
	if wallet.Balance < in.Amount {
		return nil, errorx.NewDefaultError("你没有足够的余额可以提现哦。")
	}
	wallet.Balance -= in.Amount
	wallet.UpdateTime = time.Now()
	err = l.svcCtx.WalletModel.Update(l.ctx, wallet)
	if err != nil {
		return nil, err
	}
	_, err = l.svcCtx.WalletLogModel.Insert(l.ctx, &model.WalletLog{
		Id:          l.svcCtx.Flake.Generate().Int64(),
		WalletId:    wallet.Id,
		SourceId:    in.SourceId,
		Type:        2, // 类型(1.收入 2.支出)
		OrderId:     0,
		Description: "提现",
		Amount:      in.Amount,
		Balance:     wallet.Balance,
		CreateTime:  time.Now(),
		UpdateTime:  time.Now(),
	})
	if err != nil {
		return nil, errorx.NewReasonError("网络出小差了，请重试刷新再试。", err.Error())
	}

	// 提现订单
	_, err = l.svcCtx.WalletWithdrawalModel.Insert(l.ctx, &model.WalletWithdrawal{
		Id:         l.svcCtx.Flake.Generate().Int64(),
		WalletId:   wallet.Id,
		SourceId:   in.SourceId,
		Amount:     in.Amount,
		Balance:    wallet.Balance,
		Status:     0,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
		UpdateBy:   0,
		Remark:     "",
	})
	if err != nil {
		return nil, errorx.NewReasonError("网络出小差了，请重试刷新再试。", err.Error())
	}

	go func() {
		// 通知企业微信群
		userType := "销氪"
		if wallet.SourceType == 2 {
			userType = "商家"
		}
		message := fmt.Sprintf(`{"msgtype": "markdown", "markdown": {"content": "<font color='%s'> %s</font> \n 用户姓名: %s \n 提现金额:%s\n 提现时间: %s ", "mentioned_list":["@all"], "mentioned_mobile_list": ""}}`,
			"red",
			fmt.Sprintf("%s %s", userType, "提现申请"),
			wallet.AccountName,
			fmt.Sprintf("%.2f", float64(in.Amount)/100),
			time.Now().Format(tools.YYYYMMDDHHmmSS),
		)
		resp, err := http.Post(
			in.Robot,
			"application/json",
			bytes.NewBuffer([]byte(message)))
		if err != nil {
			logx.WithContext(l.ctx).Errorf("通知企业微信群失败")
		}
		fmt.Printf("%v", resp)
	}()

	return &walletClient.EmptyBody{}, nil
}
